<!--  -->
<template>
    <form class='validate-form-container'>
        <slot></slot>
        <div class="sublit-area" @click.prevent='submitForm'>
            <slot name="submit">
                <button type="submit" class="btn btn-primary">提交</button>
            </slot>
        </div>
    </form>
</template>

<script lang='ts'>
import { defineComponent, PropType, computed, onUnmounted } from 'vue';
import mitt from 'mitt';

// 描述validateInput.vue中validateInput方法
type validateFunc = (() => boolean) | undefined
export const emitter = mitt()
export default defineComponent({
   name: 'validateForm',
   emits: ['form-submit'],
   setup(props, context) {
       let funcArr:  validateFunc[]= [];
       const submitForm = () => {
           // 有一个校验不通过，后面校验都不执行了
           // let result = funcArr.every( func => (func as Function)())
           // 都进行校验
          const  result  = funcArr.map(func => (func as Function)()).every( res => res)
          context.emit('form-submit', result)
       }

       const callback = (func: validateFunc) => {
            funcArr.push(func);
       }
       
       // 获取每个input校验函数
       emitter.on('form-item-created', callback)

      onUnmounted(() => {
        emitter.off('form-item-created', callback)
        funcArr = [];
      })

       return {
           submitForm
       }
   },
})
</script>
<style lang='scss' scoped>
</style>